import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
    state: {
			socketTask: null,
			socketOpen: false,
			dataSocket: '',			// 服务器返回的数据
		},
    mutations: {
			/* 打开连接 */
			INIT_SOCKET(state,p){
				if(state.socketOpen){console.log('不能重复打开连接');return}
				state.socketTask = uni.connectSocket({
					url: p.url,
					header: {
						"mid": p.mid,
						"token": p.token,
						"from": "BUSINESS",
						"channel": 3
					},
					success:(res)=>{
						// console.log(res,'方法成功')
					}
				})
				console.log(state.socketTask,'创建 WebSocket 实例')
				
				/* WebSocket 已连接 */
				state.socketTask.onOpen(res => {
					console.log('WebSocket 连接已打开');
					state.socketOpen=true;
				})
				
				/* WebSocket 连接失败 */
				state.socketTask.onError(res => {
					console.log('WebSocket 连接失败');
				});
				
				// /* 接收服务器返回的数据 */
				state.socketTask.onMessage(res => {
					state.dataSocket = res.data
				})
			},
			/* 发送数据 */
			SEND(state,data){
				if(!state.socketOpen){
					console.log('连接未打开')
					return
				}
				uni.sendSocketMessage({ data })
			},
			/* 关闭 WebSocket*/
			CLOSE_SOCKET(state){
				state.socketTask.close({
					code: 1000,
					reason: '手动关闭',
					success:()=>{
						console.log("WebSocket 连接已关闭")
						state.socketOpen=false
					}
				})
			}
		},
    actions: {
			initSocket({ commit },p){
				commit('INIT_SOCKET',p)
			},
			send({ commit },data){
				commit('SEND',data.data)
			},
			closeSocket({ commit }){
				commit('CLOSE_SOCKET')
			}
		}
})
export default store